<?php
session_start();
function success(){
    $result = [
        'error'=> 0,
        'message' => '成功'
    ];
    return json_encode($result);
}
function error($msg){
    $data = [
        'error'=> 1,
        'message' => $msg
    ];
    return json_encode($data);
}


if(!isset($_FILES['image'])){
    die(error('无文件上传'));
}
if($_FILES['image']['error']!= 0){
    die(error('文件上传错误'));
}
$allow =[
    'image/jpg',
    'image/png',
    'image/gif'
];
if(in_array($_FILES['image']['type'],$allow)){
    die(error("禁止上传该类型"));
}
$file_name = $_FILES['image']['name'];
$file_name = explode('.',$file_name)[1];
$file_name = md5_file($_FILES['image']['tmp_name']).time().'.'.$file_name;
$file_name = 'tmp/'.$file_name;

move_uploaded_file($_FILES['image']['tmp_name'],$file_name);



$db = new PDO('mysql:dbname=qq;host=127.0.0.1','root','123456');
$statement = $db ->prepare("update userinfo set img=:img WHERE name =:name");
$statement->execute([
    ':name' => $_SESSION['user'],
    ':img' => $file_name
]);
if($statement) {
    echo success();
}else{
    echo error('照片上传失败！');
}
$result = $statement->fetchAll();
?>
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>文件上传</title>
</head>
<body>

<img src="<?php echo $file_name ?>">
</body>
</html>
